import { Hono } from 'hono'
import { eq, ilike, desc, asc } from 'drizzle-orm'
import { nuxtdb } from '../../lib/db/database'
import { tags } from '~/utils/db/nuxt-schema'

const app = new Hono()

// 获取标签列表（支持分页和模糊查询）
app.get('/tags', async (c) => {
  try {
    const page = parseInt(c.req.query('page') || '1')
    const limit = parseInt(c.req.query('limit') || '10')
    const search = c.req.query('search') || ''
    const offset = (page - 1) * limit

    let whereCondition = undefined
    if (search) {
      whereCondition = ilike(tags.name, `%${search}%`)
    }

    const [data, total] = await Promise.all([
      nuxtdb
        .select({
          id: tags.id,
          name: tags.name,
          sortOrder: tags.sortOrder,
          remark: tags.remark,
          createdAt: tags.createdAt,
          updatedAt: tags.updatedAt
        })
        .from(tags)
        .where(whereCondition)
        .orderBy(asc(tags.sortOrder), desc(tags.createdAt))
        .limit(limit)
        .offset(offset),

      nuxtdb
        .select({ count: tags.id })
        .from(tags)
        .where(whereCondition)
    ])

    return c.json({
      success: true,
      data: data,
      pagination: {
        page,
        limit,
        total: total.length,
        totalPages: Math.ceil(total.length / limit)
      }
    })
  } catch (error) {
    console.error('获取标签列表失败:', error)
    return c.json({ success: false, message: '获取标签列表失败' }, 500)
  }
})

// 获取所有标签（用于下拉选择）
app.get('/tags/all', async (c) => {
  try {
    const data = await nuxtdb
      .select({
        id: tags.id,
        name: tags.name
      })
      .from(tags)
      .orderBy(asc(tags.sortOrder), asc(tags.name))

    return c.json({
      success: true,
      data: data
    })
  } catch (error) {
    console.error('获取所有标签失败:', error)
    return c.json({ success: false, message: '获取所有标签失败' }, 500)
  }
})

// 获取单个标签详情
app.get('/tags/:id', async (c) => {
  try {
    const id = c.req.param('id')

    const data = await nuxtdb
      .select()
      .from(tags)
      .where(eq(tags.id, id))
      .limit(1)

    if (data.length === 0) {
      return c.json({ success: false, message: '标签不存在' }, 404)
    }

    return c.json({
      success: true,
      data: data[0]
    })
  } catch (error) {
    console.error('获取标签详情失败:', error)
    return c.json({ success: false, message: '获取标签详情失败' }, 500)
  }
})

// 创建标签
app.post('/tags', async (c) => {
  try {
    const body = await c.req.json()
    const { name, sortOrder, remark } = body

    if (!name) {
      return c.json({ success: false, message: '标签名称不能为空' }, 400)
    }

    const newTag = await nuxtdb
      .insert(tags)
      .values({
        id: createId(),
        name,
        sortOrder: sortOrder || 0,
        remark: remark || null
      })
      .returning()

    return c.json({
      success: true,
      data: newTag[0],
      message: '标签创建成功'
    })
  } catch (error) {
    console.error('创建标签失败:', error)
    return c.json({ success: false, message: '创建标签失败' }, 500)
  }
})

// 更新标签
app.put('/tags/:id', async (c) => {
  try {
    const id = c.req.param('id')
    const body = await c.req.json()
    const { name, sortOrder, remark } = body

    if (!name) {
      return c.json({ success: false, message: '标签名称不能为空' }, 400)
    }

    const existingTag = await nuxtdb
      .select()
      .from(tags)
      .where(eq(tags.id, id))
      .limit(1)

    if (existingTag.length === 0) {
      return c.json({ success: false, message: '标签不存在' }, 404)
    }

    const updatedTag = await nuxtdb
      .update(tags)
      .set({
        name,
        sortOrder: sortOrder || 0,
        remark: remark || null
      })
      .where(eq(tags.id, id))
      .returning()

    return c.json({
      success: true,
      data: updatedTag[0],
      message: '标签更新成功'
    })
  } catch (error) {
    console.error('更新标签失败:', error)
    return c.json({ success: false, message: '更新标签失败' }, 500)
  }
})

// 删除标签
app.delete('/tags/:id', async (c) => {
  try {
    const id = c.req.param('id')

    const existingTag = await nuxtdb
      .select()
      .from(tags)
      .where(eq(tags.id, id))
      .limit(1)

    if (existingTag.length === 0) {
      return c.json({ success: false, message: '标签不存在' }, 404)
    }

    await nuxtdb
      .delete(tags)
      .where(eq(tags.id, id))

    return c.json({
      success: true,
      message: '标签删除成功'
    })
  } catch (error) {
    console.error('删除标签失败:', error)
    return c.json({ success: false, message: '删除标签失败' }, 500)
  }
})

export default app
